package com.slwish.xty.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.slwish.common.base.PresenterToolbarActivity;
import com.slwish.common.config.Contants;
import com.slwish.common.utils.IntentUtils;
import com.slwish.common.utils.SpUtils;
import com.slwish.common.utils.StringUtils;
import com.slwish.common.utils.TimeUtils;
import com.slwish.xty.R;
import com.slwish.xty.entity.ServiceItemsModel;
import com.slwish.xty.entity.ServiceList;
import com.slwish.xty.entity.SubscribeModel;
import com.slwish.xty.entity.UserModel;
import com.slwish.xty.mvp.contract.SubscribeEditContract;
import com.slwish.xty.mvp.presenter.SubscribeEditPresenter;
import com.slwish.xty.widget.NumberButton;
import com.slwish.xty.widget.flowlayout.FlowLayout;
import com.slwish.xty.widget.flowlayout.TagAdapter;
import com.slwish.xty.widget.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 预约住宿
 */
public class SubscribeEditActivity extends PresenterToolbarActivity<SubscribeEditContract.Presenter> implements SubscribeEditContract.View {
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_number)
    EditText etNumber;
    @BindView(R.id.et_remarks)
    EditText etRemarks;
    @BindView(R.id.flowlayout)
    TagFlowLayout flowlayout;
    @BindView(R.id.zs_number_button)
    NumberButton zsNumberButton;
    @BindView(R.id.yc_number_button)
    NumberButton ycNumberButton;
    private boolean ISSTARTTIME = true;
    private List<String> timeList;
    private UserModel userModel;
    private long usetId;
    private int merId;
    private List<ServiceList> serviceItems = new ArrayList<>();
    private Set<Integer> selectPosSet = new HashSet<>();

    @Override
    protected int getLayoutId() {
        return R.layout.act_reservate_edit;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        setTitle(R.string.server_subscribe_title);
        usetId = SpUtils.getLong(mContext, Contants.UserCode, 0);
        merId = getIntent().getIntExtra(Contants.ID, 0);
//        userModel = UserDb.query(usetId);
    }

    @Override
    protected void initData() {
        super.initData();
        mPresenter.queryServiceItems();
    }

    @Override
    protected void initEvent() {
        super.initEvent();

        flowlayout.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set<Integer> selectPosSet) {
                SubscribeEditActivity.this.selectPosSet = selectPosSet;

            }
        });
    }

    @Override
    public void submitSuccess(SubscribeModel model) {
        Bundle bundle = new Bundle();
        bundle.putSerializable(Contants.MODEL,model);
        IntentUtils.startActivity(mContext,SubscribeSuccessActivity.class,bundle);
        finish();
    }

    /**
     * 查询服务项目返回
     */
    @Override
    public void queryServiceSuccess(ServiceItemsModel model) {
        serviceItems = model.getData();
        List<String> mLists = new ArrayList<>();
        for (ServiceList servicrItems : serviceItems) {
            mLists.add(servicrItems.getServiceName());
        }
        flowlayout.removeAllViews();
        flowlayout.setAdapter(new TagAdapter<String>(mLists) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView view = (TextView) LayoutInflater.from(mContext).inflate(R.layout.view_service_items_text,
                        parent, false);
                view.setText(s);
                return view;
            }
        });
    }

    @Override
    protected SubscribeEditContract.Presenter initPresenter() {
        return new SubscribeEditPresenter(this);
    }

    @OnClick({R.id.tv_submit, R.id.ll_start_time, R.id.ll_end_time})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_submit://提交
                String serviceItem = "";
                if (serviceItems != null && serviceItems.size() > 0 && selectPosSet != null && selectPosSet.size() > 0) {
                    Iterator it = selectPosSet.iterator(); // 获得一个迭代子
                    while (it.hasNext()) {
                        int obj = (int) it.next(); // 得到下一个元素
                        serviceItems.get(obj).getId();
                        serviceItem = serviceItem + serviceItems.get(obj).getId() + ",";
                    }
                    serviceItem = serviceItem.substring(0, serviceItem.length() - 1);
                }
                mPresenter.submitSubscribe(mContext, usetId + "", merId + "", etName.getText().toString()
                        , etNumber.getText().toString(), tvStartTime.getText().toString()
                        , tvEndTime.getText().toString(), zsNumberButton.getNumber() + ""
                        , ycNumberButton.getNumber() + "", etRemarks.getText().toString(), serviceItem);
                break;
            case R.id.ll_start_time://选择时间
                Bundle bundle = new Bundle();
                ISSTARTTIME = true;
                bundle.putBoolean("ISSTARTTIME", ISSTARTTIME);
                IntentUtils.startActivityForResult(mContext, ChoseTimeActivity.class, bundle, Contants.REQUESTCODE_FROM_ACTIVITY);
                break;
            case R.id.ll_end_time://选择时间
                ISSTARTTIME = false;
                Bundle bundles = new Bundle();
                bundles.putBoolean("ISSTARTTIME", ISSTARTTIME);
                IntentUtils.startActivityForResult(mContext, ChoseTimeActivity.class, bundles, Contants.REQUESTCODE_FROM_ACTIVITY);
                break;
        }
    }

    /**
     * onActivityResult
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            //入住、离开时间处理
            if (requestCode == Contants.REQUESTCODE_FROM_ACTIVITY) {
                //没数据直接return
                if (data == null) return;
                timeList = data.getStringArrayListExtra("list");
                if (timeList != null) {
                    if (timeList.size() == 1) {
                        //当前选择的单个时间;可以是开始时间 也可以是结束时间
                        long nowTime = Long.valueOf(timeList.get(0).toString());
                        String startTime = TimeUtils.milliseconds2String(nowTime, TimeUtils.NO_HOUR_SDF);
                        if (ISSTARTTIME) {//判断是选择的开始时间，还是结束时间true:设置开始时间 false :设置结束时间
                            tvStartTime.setText(startTime);
                            //如果当钱选择的开始时间大于之前选择的结束时间，则删除结束时间，以开始时间的时间节点为开始点
                            if (!StringUtils.isEmpty(tvEndTime.getText().toString())) {
                                long endTime = TimeUtils.string2Milliseconds(tvEndTime.getText().toString(), TimeUtils.NO_HOUR_SDF);
                                //当前选择的开始时间大于之前的结束时间，以现在选择的开始时间为主，去掉old的结束时间
                                if ((nowTime - endTime) > 0) {
                                    tvEndTime.setText("");
                                }
                            }
                        } else {
                            tvEndTime.setText(startTime);
                            //如果当钱选择的开始时间大于之前选择的结束时间，则删除结束时间，以开始时间的时间节点为开始点
                            if (!StringUtils.isEmpty(tvStartTime.getText().toString())) {
                                long oldstartTime = TimeUtils.string2Milliseconds(tvStartTime.getText().toString(), TimeUtils.NO_HOUR_SDF);
                                if ((nowTime - oldstartTime) < 0) {
                                    tvStartTime.setText("");
                                }
                            }
                        }
                    } else {//选择的是多个时间点
                        String time1 = timeList.get(0).toString();
                        String time2 = timeList.get(1).toString();
                        String startTime = TimeUtils.milliseconds2String(Long.valueOf(time1), TimeUtils.NO_HOUR_SDF);
                        String endTime = TimeUtils.milliseconds2String(Long.valueOf(time2), TimeUtils.NO_HOUR_SDF);
                        tvStartTime.setText(startTime);

                        tvEndTime.setText(endTime);

                    }
                }
            }
        } catch (Exception e) {
        }
    }
}
